package Homework;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//服务器端
public class Server {
/*
 * main所在的主线程循环接收客户端的请求
 * 让子线程专门处理与客户端的IO操作
 */
	public static void main(String[] args) {
		//创建serversocket套接字
		ServerSocket serverSocket=null;
		Socket socket=null;
		try {
			serverSocket = new ServerSocket(9990);
			System.out.println("服务器已启动。。。。。。");
			while(true) {
				//服务器接收客户端的请求
				socket= serverSocket.accept();
				
				System.out.println("已受理客户端"+socket.getInetAddress().getHostName()+"："+socket.getPort()+"的请求！");
				//启动线程
				new Thread(new IORun(socket)).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				socket.close();
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


class IORun implements Runnable{

	private Socket Socket;
	
	public Socket getSocket() {
		return Socket;
	}

	public void setSocket(Socket socket) {
		Socket = socket;
	}
	

	public IORun(java.net.Socket socket) {
		super();
		Socket = socket;
	}
	

	public IORun() {
		super();
	}

	@SuppressWarnings("resource")
	@Override
	public void run() {
		//让服务器端和客户端可以不断地循环交流
		//通过键盘输入
		Scanner scanner = new Scanner(System.in);
		DataInputStream dis=null;
		DataOutputStream dos=null;
		//先让客户端给服务器发信息
		try {
			dis = new DataInputStream(Socket.getInputStream());
			dos = new DataOutputStream(Socket.getOutputStream());
			//循环接收客户端发来的信息
			while(true) {
				String infoFromCLient = dis.readUTF();
				System.out.println("客户端对服务器"+Socket.getInetAddress().getHostName()+"说："+infoFromCLient);
				System.out.print("服务器对客户端"+Socket.getInetAddress().getHostName()+"说：");
				String infoToClient=scanner.next();
				//将服务器的回复写给客户端
				dos.writeUTF(infoToClient);
				System.out.println("等待客户端"+Socket.getPort()+"的响应。。。");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				dos.close();
				dis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}